package com.googlecode.aleverr.yafotkiclient.ui.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.googlecode.aleverr.yafotkiclient.R;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AuthActivity extends Activity {

    private static final String TAG = "AuthActivity";

    private static final Pattern ACCESS_TOKEN_PATTERN = Pattern.compile("^access_token=([0-9a-f]+)&");

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Uri uri = Uri.parse(url);
            if ("yfc".equals(uri.getScheme())) {
                Log.d(TAG, "YFC: " + url);
                String fragment = uri.getFragment();
                if (fragment != null) {
                    Matcher matcher = ACCESS_TOKEN_PATTERN.matcher(fragment);
                    if (matcher.find()) {
                        String accessToken = matcher.group(1);
                        if (accessToken != null) {
                            Log.d(TAG, "Access token: " + accessToken);
                            finishWithAccessToken(accessToken);
                        }
                    }
                }
                Log.d(TAG, "Cannot match a token");
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }
    }

    public void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.auth);

        WebView webView = (WebView) findViewById(R.id.auth_webview);
        webView.getSettings().setSavePassword(false);
        webView.setWebViewClient(new MyWebViewClient());
        webView.loadUrl("https://oauth.yandex.ru/authorize?response_type=token&client_id=79b46da40f374c22b8812736c3d9def4&display=popup");
    }

    private void finishWithAccessToken(String accessToken) {
        Intent intent = getIntent();
        intent.putExtra("accessToken", accessToken);
        setResult(RESULT_OK, intent);
        finish();
    }
}